package com.rlz.net.Interceptor

import android.util.Log
import com.rlz.net.BuildConfig
import okhttp3.Interceptor
import okhttp3.Response
import java.nio.charset.Charset
import java.nio.charset.StandardCharsets

/**
 * Created by RLZ
 * on 2021/3/8
 *
 */
class RequestInterceptor : Interceptor {

    override fun intercept(chain: Interceptor.Chain): Response {
        val request = chain.request()
        val newBuilder = request.newBuilder();
        newBuilder.removeHeader("Accept-Encoding")

        if (request.method == "PATCH")
            newBuilder.header("x-http-method-override", "PATCH")

        val build = newBuilder.build()

        val response = chain.proceed(build)

        if (response.isSuccessful) {
            if (BuildConfig.DEBUG) {
                val body = response.body
                val source = body!!.source();
                source.request(Long.MAX_VALUE)
                val buffer = source.buffer();
                val contentType = body.contentType();
                val charset: Charset = StandardCharsets.UTF_8
                contentType!!.charset(charset)
                val contentLength = body.contentLength()
                if (contentLength != 0L) {
                    val readString = buffer.clone().readString(charset)
                    Log.d("data", readString);
                }
            }
        }
        return response;
    }
}